<template>
  <view class="appointments-container">
    <!-- 预约列表 -->
    <view class="appointments-list">
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <view v-else-if="appointments.length === 0" class="empty">
        <text>暂无预约记录</text>
      </view>
      
      <view v-else class="list-content">
        <view 
          v-for="(appointment, index) in appointments" 
          :key="appointment.id || index"
          class="appointment-item"
        >
          <!-- 活动信息 -->
          <view class="activity-info">
            <image 
              class="activity-image" 
              :src="appointment.activityCover || '/static/images/default-activity.jpg'"
              mode="aspectFill"
              @error="onImageError(index)"
            ></image>
            <view class="activity-details">
              <text class="activity-name">{{ appointment.activityName }}</text>
              <text class="activity-time">{{ formatDateTime(appointment.activityStartTime) }}</text>
              <text class="activity-location">{{ appointment.activityLocation }}</text>
            </view>
          </view>
          
          <!-- 就诊人信息 -->
          <view class="patient-info">
            <text class="patient-label">就诊人：</text>
            <text class="patient-name">{{ appointment.patientName }}</text>
            <text class="patient-age">{{ appointment.patientAge }}岁</text>
            <text class="patient-gender">{{ getGenderText(appointment.patientGender) }}</text>
          </view>
          
          <!-- 报名状态 -->
          <view class="registration-status">
            <text class="status-label">报名状态：</text>
            <text class="status-text" :class="getStatusClass(appointment.status)">
              {{ getStatusText(appointment.status) }}
            </text>
          </view>
          
          <!-- 报名时间 -->
          <view class="registration-time">
            <text class="time-label">报名时间：</text>
            <text class="time-text">{{ formatDateTime(appointment.registrationTime) }}</text>
          </view>
          
          <!-- 备注信息 -->
          <view class="remark-info" v-if="appointment.remark">
            <text class="remark-label">备注：</text>
            <text class="remark-text">{{ appointment.remark }}</text>
          </view>
          
          <!-- 操作按钮 -->
          <view class="actions" v-if="appointment.status === 'PENDING'">
            <button 
              class="action-btn cancel" 
              size="mini" 
              @click="cancelAppointment(appointment)"
            >
              取消报名
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'MyAppointments',
  data() {
    return {
      appointments: [],
      loading: false
    }
  },
  
  onLoad() {
    this.loadAppointments();
  },
  
  onShow() {
    this.loadAppointments();
  },
  
  methods: {
    // 加载预约列表
    async loadAppointments() {
      this.loading = true;
      try {
        const token = uni.getStorageSync('token');
        if (!token) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          return;
        }
        
        const response = await uni.request({
          url: this.$baseUrl + '/activity-registration/user/list',
          method: 'GET',
          header: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token
          }
        });
        
        if (response.statusCode === 200 && response.data.code === 200) {
          this.appointments = response.data.data || [];
        } else {
          uni.showToast({
            title: response.data.message || '获取预约列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取预约列表失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 取消报名
    async cancelAppointment(appointment) {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消这个报名吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token');
              const response = await uni.request({
                url: this.$baseUrl + `/activity-registration/${appointment.id}/cancel`,
                method: 'POST',
                header: {
                  'Content-Type': 'application/json',
                  'Authorization': 'Bearer ' + token
                }
              });
              
              if (response.statusCode === 200 && response.data.code === 200) {
                uni.showToast({
                  title: '取消成功',
                  icon: 'success'
                });
                this.loadAppointments();
              } else {
                uni.showToast({
                  title: response.data.message || '取消失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              console.error('取消报名失败:', error);
              uni.showToast({
                title: '网络错误，请稍后重试',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    
    // 获取性别文本
    getGenderText(gender) {
      switch (gender) {
        case 1:
          return '男';
        case 2:
          return '女';
        case 3:
          return '其他';
        default:
          return '未知';
      }
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      switch (status) {
        case 'PENDING':
          return 'pending';
        case 'CONFIRMED':
          return 'confirmed';
        case 'CANCELLED':
          return 'cancelled';
        default:
          return 'pending';
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'PENDING':
          return '待确认';
        case 'CONFIRMED':
          return '已确认';
        case 'CANCELLED':
          return '已取消';
        default:
          return '待确认';
      }
    },
    
    // 图片加载错误
    onImageError(index) {
      this.appointments[index].activityCover = '/static/images/default-activity.jpg';
    }
  }
}
</script>

<style scoped>
.appointments-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 10px;
}

.loading, .empty {
  text-align: center;
  padding: 50px 20px;
  color: #999;
  font-size: 14px;
}

.appointment-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.activity-info {
  display: flex;
  margin-bottom: 15px;
}

.activity-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  margin-right: 12px;
}

.activity-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.activity-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.activity-time, .activity-location {
  font-size: 12px;
  color: #666;
  margin-bottom: 3px;
}

.patient-info, .registration-status, .registration-time, .remark-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.patient-label, .status-label, .time-label, .remark-label {
  color: #999;
  margin-right: 5px;
  min-width: 70px;
}

.patient-name {
  color: #333;
  font-weight: bold;
  margin-right: 8px;
}

.patient-age, .patient-gender {
  color: #666;
  margin-right: 8px;
}

.status-text {
  font-weight: bold;
}

.status-text.pending {
  color: #faad14;
}

.status-text.confirmed {
  color: #52c41a;
}

.status-text.cancelled {
  color: #ff4d4f;
}

.time-text {
  color: #333;
}

.remark-text {
  color: #666;
  flex: 1;
}

.actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.action-btn {
  margin-left: 10px;
}

.action-btn.cancel {
  background-color: #ff4d4f;
  color: #fff;
}
</style> 